import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View} from '@tarojs/components'
import {AtInput, AtSwitch, AtInputNumber, AtButton} from 'taro-ui'
import {MD_PAY_TOKEN, CANCEL_PAY, MD_CAN_USE_JF, MD_PAY} from "../../constants/api";
import {GetRequest, debounce} from "../../utils/tools";
import {newHttp} from "../../utils/request";
import {payment} from "../../utils/payment.service";
import {user} from "../../utils/user.service";
import {getGlobalData} from "../../utils/global"
import './buyorder.scss'

export default class BuyOrder extends Component {
  state: {
    url: string
    orderForm: {
      price: string
    }
    getFee: {
      jf: number
    }
    loading: boolean
    alldisable: boolean
    useIntegral: boolean
    orderNum: string
    supplierName: string
    supplier_id: string
    check_group_id: string
    useJf: boolean
    payToken: string
    integral: number
    isDis: boolean
  } = {
    url: '',
    orderForm: {
      price: ''
    },
    getFee: {
      jf: 0
    },
    loading: true,
    alldisable: true,
    useIntegral: true,
    integral: 0,
    orderNum: '',
    supplierName: '',
    supplier_id: '',
    check_group_id: '',
    useJf: true,
    payToken: '',
    isDis: false,
    payTokenTimer: null,
    canSubmit: false
  }

  async componentDidShow() {
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      user.jumpLogin()
    }
    const isuseJf = await newHttp.catchPost(MD_CAN_USE_JF)
    const paramsArr = Taro.getCurrentInstance().router.params.orderNum.split('_')
    this.state.orderNum = paramsArr[0]
    this.state.supplierName = paramsArr[1]
    Taro.setNavigationBarTitle({
      title: this.state.supplierName
    })
    this.setState({
      orderNum: this.state.orderNum,
      supplierName: this.state.supplierName,
      check_group_id: paramsArr.length > 2 ? paramsArr[2] : '',
      supplier_id: paramsArr.length > 2 ? paramsArr[3] : '',
      useJf: isuseJf
    }, async () => {
      const ret = await this.getPayToken(true)
      this.state.orderNum = ret.order_num
    })
  }

  mdPayDebounce() {
    debounce(this.mdPay(), 2000)
  }

  async mdPay() {
    !!this.payTokenTimer && clearTimeout(this.payTokenTimer);
    const {loading, orderNum, payToken} = this.state
    if (loading) return
    this.setState({loading: true, isDis: true})
    const ret = await newHttp.catchPost(MD_PAY + orderNum, {payToken: payToken['payToken']})
    if (ret) {
      const payRet = await payment.payment(ret, false, async res => {
        if (res.errMsg.includes('ok')) {
          Taro.redirectTo({url: '/main/order/success?pay=' + payToken.origin_fee + '&typeName=md'})
        }
      })
      if (!payRet) {
        await newHttp.catchPost(CANCEL_PAY + orderNum)
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.switchTab({url: '/pages/index/index'})
        }, 2000)
      }
    }else {
      this.setState({loading: false, isDis: false})
    }
  }

  timer

  async getPayToken(isIntegral) {
    if (this.state.isDis) return
    const {price} = this.state.orderForm
    const {supplier_id, check_group_id} = this.state
    const total_fee = price ? price.replace('¥', '') : 0
    let payToken = await newHttp.catchPost(MD_PAY_TOKEN + this.state.orderNum, {
      total_fee,
      use_integral: this.state.useIntegral ? this.state.integral : 0,
      supplier_id,
      check_group_id
    })
    if (total_fee > 0 && isIntegral) {
      const integral = payToken.max_jf
      payToken = await newHttp.catchPost(MD_PAY_TOKEN + this.state.orderNum, {
        total_fee,
        use_integral: this.state.useIntegral ? integral : 0,
        supplier_id,
        check_group_id
      })
      this.setState({payToken, integral: payToken.max_jf})
    } else {
      this.setState({payToken})
    }
    setTimeout(() => {
      this.setState({canSubmit: true})
    }, 0)
    return payToken
  }

  async payToken(isIntegral = true) {
    !!this.payTokenTimer && clearTimeout(this.payTokenTimer);
    await this.getPayToken(isIntegral)
  }

  handleChange(name, value, e) {
    if (e.type === "input") {
      this.payTokenTimer && clearTimeout(this.payTokenTimer);

      this.setState(state => ({
        loading: true,
        orderForm: {
          ...state.orderForm,
          price: value,
        },
        canSubmit: false
      }), () => {
        let {loading, alldisable, payToken} = this.state;
        if (+value) {
          this.payTokenTimer = setTimeout(async () => {
            clearTimeout(this.payTokenTimer);
            loading = false;
            alldisable = false;
            this.setState({loading, alldisable});
            await this.payToken();
          }, 200)
        } else {
          loading = false;
          alldisable = true;
          payToken = "";
          this.setState({alldisable, payToken});
        }
      })
    }
  }

  handleBlur = async () => {
    // Blur事件滞后于支付事件, 导致payToken不是最新的, 支付接口报错
    // !!this.payTokenTimer && clearTimeout(this.payTokenTimer);
    // this.state.orderForm.price !== "" && await this.payToken();
  }

  integralSwitch(value) {
    this.setState({loading: true}, async () => {
      if (this.state.alldisable || !this.state.orderForm.price) {
        this.setState({useIntegral: false})
        Taro.showToast({title: '请先输入消费总额', icon: 'none'})
        return
      }
      this.setState({useIntegral: value, integral: value ? this.state.payToken.max_jf : 0}, () => {
        this.payToken()
      })
    })
  }

  integralChangebtn(val) {
    const {getFee} = this.state
    getFee.jf = val
    this.setState({getFee, integral: val, loading: true}, async () => {
      await this.payToken(false)
    })
  }

  jumpPage(url) {
    Taro.navigateTo({url})
  }

  render() {
    const {orderForm, loading, useJf, payToken, useIntegral, integral, alldisable, isDis, canSubmit} = this.state
    return (
      <View className='buyorder-root '>
        <View className='top-box'>
          <View className='price-total-box common'>
            <View className=''>消费总额:</View>
            <View className=''>
              <AtInput
                name='price'
                type='digit'
                maxLength={8}
                placeholder='请输入消费总额'
                value={orderForm.price}
                onChange={this.handleChange.bind(this, 'price')}
                onBlur={this.handleBlur}
              />
            </View>
          </View>
          {useJf && payToken && payToken.max_jf > 0 && <View className='integral-wrap f-c-b common'>
            <View className='lt'>{getGlobalData()}</View>
            <View className='integral f-c-b'>
              <View className='use-tyb'>可抵扣{payToken.max_jf || 0}</View>
              <AtSwitch checked={useIntegral} border={false} disabled={alldisable || isDis}
                onChange={this.integralSwitch.bind(this)}
                color='#FFA000'
              />
              <View className='useIntegral-num-box'>
                {useIntegral && payToken.exchange_type == 1 ? <View className='integral-box'>
                    <View className='number'>
                      <AtInputNumber type='number' value={integral}
                        max={payToken.max_jf}
                        onChange={this.integralChangebtn.bind(this)}
                      />
                    </View>
                  </View>
                  :
                  <View />
                }
                {useIntegral && <View className='j-num'>
                  -¥{payToken.integral_deduction || 0}
                </View>}
              </View>
            </View>
          </View>}
          <View className='shifu-porice-box common f-c-b'>
            <View className='lt'>实付金额</View>
            <View className='rt'>¥{payToken.total_fee || 0}</View>
          </View>
        </View>
        <View className='submit-box'>
          <AtButton ref={this.buyButtonRef} onClick={this.mdPayDebounce.bind(this)} disabled={!orderForm.price || !canSubmit}
            className='btn buy-btn'
          >{payToken.total_fee || 0}元 确认买单</AtButton>
          <View className='tips-box f-c-b'>
            <View className='lt'>买单仅限于到店支付，请确认金额后提交</View>
            <View onClick={this.jumpPage.bind(this, '/other/buy-order/billingdetail')} className='rt'>账单明细</View>
          </View>
        </View>
      </View>
    );
  }
}
